
<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>订单管理</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-tab layui-tab-brief">
      <ul class="layui-tab-title">
        <li class="layui-this">支付订单</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row">
            <div class="layui-form" style="float:right; margin-bottom: 10px;">
              <div class="layui-form-item" style="margin:0;">
                <div class="layui-input-inline">
                  <input type="text" name="createTimeStart" id="createTimeStart" autocomplete="off" placeholder="开始时间" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="createTimeEnd" id="createTimeEnd" autocomplete="off" placeholder="结束时间" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="mchId" id="mchId" placeholder="商户ID" autocomplete="off" class="layui-input">
                </div> 
                <div class="layui-input-inline">
                  <input type="text" name="passageAccountId" id="passageAccountId" placeholder="账号ID" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="payOrderId" id="payOrderId" placeholder="支付订单号" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="mchOrderNo" id="mchOrderNo" placeholder="商户订单号" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                <select name="channelId" id="channelId" lay-search="">
                <option value="-99">支付通道</option>
                </select>
                </div>
                <div class="layui-input-inline">
                  <select name="productId" id="productId" lay-search="">
                    <option value="-99">支付产品</option>
                  </select>
                </div>
                <div class="layui-input-inline" style="margin-top:10px;">
                  <select name="type" id="productType" placeholder="产品类型" lay-search="">
                    <option value="-99">产品类型</option>
                    <option value="1">收款</option>
                    <option value="2">充值</option>
                  </select>
                </div>
                <div class="layui-input-inline" style="margin-top:10px;">
                  <select name="status" id="status" lay-search="">
                    <option value="-99">订单状态</option>
                    <option value="0">订单生成</option>
                    <option value="1">支付中</option>
                    <option value="2">支付成功</option>
                    <option value="-1">支付失败</option>
                    <option value="3">处理完成</option>
                    <option value="4">已退款</option>
                  </select>
                </div>
                <button id="search" class="layui-btn" style="margin-top:10px;" data-type="reload">搜索</button>
              </div>
            </div>
            <div class="layui-form-item">
              <blockquote class="layui-elem-quote" id="amountTip">
                提交订单数:<sapn id="allTotalCount" style="color: blue; margin-right: 10px;"></sapn>
                订单总金额:<span id="allTotalAmount" style="color: blue; margin-right: 10px;"></span>
                已付订单数:<span id="successTotalCount" style="color: green; margin-right: 10px;"></span>
                已付总金额:<span id="successTotalAmount" style="color: green; margin-right: 10px;"></span>
                商户总收入:<span id="successTotalMchIncome" style="color: green; margin-right: 10px;"></span>
                代理商收入:<span id="successTotalAgentProfit" style="color: green; margin-right: 10px;"></span>
                平台收入:<span id="successTotalPlatProfit" style="color: green; margin-right: 10px;"></span>
                未付订单数:<span id="failTotalCount" style="color: red; margin-right: 10px;"></span>
                未付总金额:<span id="failTotalAmount" style="color: red; margin-right: 10px;"></span>
                成功率:<span id="successRate" style="color: red; margin-right: 10px;"></span>
              </blockquote>
            </div>
          </div>
          <table id="JeePay_Mgr_PayOrder_dataAll" lay-filter="JeePay_Mgr_PayOrder_dataAll"></table>
        </div>

      </div>
    </div>
  </div>
</div>

<script type="text/html" id="jeepayBar">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="channelOrderQuery">上游结果</a>
  {{#  if(d.status == 1){ }}
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="reissue">补单</a>
  {{#  } else { }}
  <a class="layui-btn layui-btn-primary layui-btn-xs layui-btn-disabled" lay-event="reissue">补单</a>
  {{#  } }}
</script>

<script>
   var channelIds = {} ;
   var merchantIds = {} ;
  layui.use(['admin', 'table', 'util', 'laydate'], function(){
    var $ = layui.$
            ,admin = layui.admin
            ,table = layui.table
            ,element = layui.element
            ,laydate = layui.laydate
            ,form = layui.form;

    element.render('breadcrumb', 'breadcrumb');

    $.setCountResult = function(mchId,channelId,passageAccountId,productId, payOrderId, mchOrderNo, productType, createTimeStart, createTimeEnd) {
      admin.req({
        type: 'get',
        url: layui.setter.baseUrl + '/pay_order/count',
        data: {
          mchId : mchId,
          channelId : channelId,
          passageAccountId : passageAccountId,
          productId : productId,
          payOrderId : payOrderId,
          mchOrderNo : mchOrderNo,
          productType : productType,
          createTimeStart : createTimeStart,
          createTimeEnd : createTimeEnd
        },
        error: function(err){
          layer.alert(JSON.stringify(err.field), {
            title: '错误提示'
          })
        },
        success: function(res){
          if(res.code == 0){
            $('#allTotalCount').html(res.data.allTotalCount);
            $('#allTotalAmount').html("￥" + res.data.allTotalAmount/100.00);
            $('#successTotalCount').html(res.data.successTotalCount);
            $('#successTotalAmount').html("￥" + res.data.successTotalAmount/100.00);
            $('#successTotalMchIncome').html("￥" + res.data.successTotalMchIncome/100.00);
            $('#successTotalAgentProfit').html("￥" + res.data.successTotalAgentProfit/100.00);
            $('#successTotalPlatProfit').html("￥" + res.data.successTotalPlatProfit/100.00);
            $('#failTotalCount').html(res.data.failTotalCount);
            $('#failTotalAmount').html("￥" + res.data.failTotalAmount/100.00);
            $('#successRate').html((res.data.successTotalCount/res.data.allTotalCount*100).toFixed(2) + "%");
          }
          if(res.data.successTotalCount/res.data.allTotalCount*100 >= 50){
            $("#successRate")[0].style.color="green";
          }else {
            $("#successRate")[0].style.color="red";
          }
        }
      });
    };

    // 加载支付产品
    admin.req({
      type: 'post',
      url: layui.setter.baseUrl + '/config/common/pay_product_all',
      error: function(err){
        layer.alert(err);
      },
      success: function(res){
        if(res.code == 0){
          var payProductList = res.data;
          //遍历赋值
          for(var i in payProductList){
            $("#productId").append('<option value= '+payProductList[i].id+'>'+payProductList[i].productName+'</option>');
          }
          form.render('select');
        }
      }
    });


    // 加载支付通道
    admin.req({
      type: 'post',
      url: layui.setter.baseUrl + '/config/common/pay_passage_all',
      error: function(err){
        layer.alert(err);
      },
      success: function(res){
        if(res.code == 0){
          var channelIdList = res.data;
          channelIds = res.data;
          //遍历赋值
          for(var i in channelIdList){
            $("#channelId").append('<option value= '+channelIdList[i].ifCode+'>'+channelIdList[i].passageName+'</option>');
          }
          form.render('select');
        }
      }
    });

    /**
     * 模板化支付通道
     * @param d
     * @returns {Document.passageName}
     */
    var tpChannel = function(d){
      for(var i in channelIds){
        if (d.channelId == channelIds[i].ifCode) {
          return channelIds[i].passageName;
        }
        return d.channelId;
      }
    }

    /**
     * 模板化支付状态
     * @param d
     * @returns {string}
     */
    var tplStatus = function(d){
      if(d.status == 0) {
        return "<span style='color: blue'>订单生成</span>";
      }else if(d.status == 1) {
        return "<span style='color: orangered'>支付中</span>";
      }else if(d.status == 2) {
        return "<span style='color: green'>支付成功</span>";
      }else if(d.status == -1) {
        return "<span style='color: red'>支付失败</span>";
      }else if(d.status == 3) {
        return "<span style='color: darkgreen'>处理完成</span>";
      }else if(d.status == 4) {
        return "<span style='color: red'>已退款</span>";
      }
    };

    // 加载所有商户信息
    admin.req({
      type: 'post',
      url: layui.setter.baseUrl + '/mch_info/list',
      error: function(err){
        layer.alert(err);
      },
      success: function(res){
        if(res.code == 0){
          merchantIds = res.data;
        }
      }
    });

    /**
     * 模板化商户名
     * @param d
     * @returns {string}
     */
    var tpMerchant = function(d){
      for(var i in merchantIds){
        if (d.mchId == merchantIds[i].mchId) {
          return merchantIds[i].name + "(" + merchantIds[i].mchId + ")";
        }
        return d.mchId;
      }
    }

    // 初始化统计结果
    $.setCountResult();

    //用户列表
    table.render({
      elem: '#JeePay_Mgr_PayOrder_dataAll'
      ,url: layui.setter.baseUrl + '/pay_order/list' //用户列表接口
      ,where: {
        access_token: layui.data(layui.setter.tableName).access_token
      }
      ,id: 'tableReload'
      ,page: true
      ,cols: [[
        {type: 'checkbox', fixed: 'left'}
        //,{field: 'mchId', title: '商户ID', templet:tpMerchant}
        ,{field: 'mchId', title: '商户ID', width: 120}
        //,{field: 'mchName', title: '商户名', width: 120}
        ,{field: 'payOrderId', title: '支付单号', width: 240}
        ,{field: 'mchOrderNo', title: '商户单号'}
        //,{field: 'channelId', title: '产品通道',templet: tpChannel}
        ,{field: 'channelId', title: '产品通道'}
        ,{field: 'amount', title: '金额', width:80, templet: '<div>{{ d.amount/100 }}</div>'}
        ,{field: 'productType', title: '产品类型', width: 120, templet: '<div>{{ d.productType == 1 ? "收款" : d.productType == 2 ? "充值" : ""}}</div>'}
        ,{field: 'status', title: '状态', templet: tplStatus}
        ,{field: 'createTime', title: '创建时间', templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}
        ,{field: 'edit', title: '操作', toolbar: '#jeepayBar' }
      ]]
      ,skin: 'line'
    });

    //监听工具条
    table.on('tool(JeePay_Mgr_PayOrder_dataAll)', function(obj){
      var data = obj.data;
      if(obj.event === 'detail'){
        location.href = layui.setter.baseLocal + "order/pay/view.html?" + data.payOrderId;
      }else if(obj.event === 'reissue') {
        var payOrderId = data.payOrderId;
        layer.prompt({
          formType: 1,
          title: '确认补单，请输入超级密码：'
        }, function(value, index, elem){
          layer.close(index);
          var load = layer.msg('重新发送中...', {
            icon: 16
            ,shade: 0.01
            ,time: 9999999999
          });
          admin.req({
            type: 'post',
            url: layui.setter.baseUrl + '/pay_order/reissue',
            timeout: 1000 * 60,
            data:{
              payOrderId: payOrderId,
              password: value
            },
            error: function(err){
              layer.close(load);
              layer.alert(err);
            },
            success: function(res){
              layer.close(load);
              if(res.code == 0){
                layer.alert("补单完成，请注意查看状态！");
                table.reload("tableReload");
              }
            }
          });
        });
      } else if(obj.event === 'channelOrderQuery') {
        layer.msg('正在查询渠道订单结果...', {icon: 16});
        admin.req({
          type: 'post',
          url: layui.setter.baseUrl + '/pay_order/channel_order_query',
          data: {
            payOrderId: data.payOrderId
          },
          error: function(err){
            layer.alert(err);
          },
          success: function(res){
            layer.closeAll('loading');
            if(res.code == 0){
              layer.open({
                title: '订单:' + data.payOrderId
                ,content: res.data
              });
            }
          }
        });
      }
    });

    // 搜索
    var $ = layui.$, active = {
      reload: function(){
        var mchId = $('#mchId').val();
        var channelId = $('#channelId').val();
        var passageAccountId = $('#passageAccountId').val();
        var productId = $('#productId').val();
        var payOrderId = $('#payOrderId').val();
        var mchOrderNo = $("#mchOrderNo").val();
        var productType = $("#productType").val();
        var createTimeStart = $('#createTimeStart').val();
        var createTimeEnd = $('#createTimeEnd').val();
        var status = $("#status").val();

        $.setCountResult(mchId, channelId,passageAccountId,productId, payOrderId, mchOrderNo, productType, createTimeStart, createTimeEnd);
        //执行重载
        table.reload('tableReload', {
          page: {
            curr: 1 //重新从第 1 页开始
          }
          ,where: {
            mchId: mchId,
            channelId: channelId,
            passageAccountId: passageAccountId,
            productId: productId,
            payOrderId: payOrderId,
            mchOrderNo: mchOrderNo,
            productType: productType,
            status : status,
            createTimeStart : createTimeStart,
            createTimeEnd : createTimeEnd
          }
        });
      }
    };
    $('#search').on('click', function() {
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });

    laydate.render({
      elem: '#createTimeStart'
      ,type: 'datetime'
      ,format: 'yyyy-MM-dd HH:mm:ss'
    });

    laydate.render({
      elem: '#createTimeEnd'
      ,type: 'datetime'
      ,format: 'yyyy-MM-dd HH:mm:ss'
    });
    // 渲染表单
    form.render();
  });
</script>